import serial
import time
import math
import threading
from collections import deque
from datetime import datetime
import signal
import sys
from simple_pid import PID  # 引入PID库

class MotorDriver:
    # CRC-CCITT查找表
    CRC_CCITT_TABLE = [
	0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
	0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
	0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
	0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
	0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
	0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
	0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
	0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
	0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
	0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
	0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
	0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
	0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
	0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
	0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
	0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
	0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
	0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
	0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
	0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
	0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
	0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
	0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
	0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
	0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
	0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
	0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
	0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
	0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
	0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
	0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
	0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
    ]

    def __init__(self, port='/dev/ft232h_serial', baudrate=4000000):
        self.serial = serial.Serial(
            port=port,
            baudrate=baudrate,
            timeout=0.005,  # 改为5ms
            write_timeout=0.005
        )
        self.REDUCTION_RATIO = 6.33
        
        self._running = False
        self._lock = threading.Lock()
        self._motor_commands = {i: {'torque': 0} for i in range(2)}
        self._motor_status = {i: deque(maxlen=10) for i in range(2)}
        self._last_status = {}
        self._target_speeds = {i: 0 for i in range(2)}  # 目标转速
        self._pids = {i: PID(1.0, 0.1, 0.05, setpoint=0) for i in range(2)}  # 初始化PID控制器
        
        # 注册信号处理函数
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)
        
        self.start_comm()

    def start_comm(self):
        """启动通信线程"""
        if not self._running:
            self._running = True
            self._comm_thread = threading.Thread(target=self._comm_loop)
            self._comm_thread.daemon = True
            self._comm_thread.start()

    def stop_comm(self):
        """停止通信线程"""
        self._running = False
        if self._comm_thread:
            self._comm_thread.join()

    def _comm_loop(self):
        """通信主循环"""
        period = 0.005  # 5ms，200Hz
        
        while self._running:
            loop_start = time.time()
            
            # 清理过多的缓存数据
            if self.serial.in_waiting > 32:
                self.serial.reset_input_buffer()
            
            # 发送命令
            with self._lock:
                for motor_id in [0, 1]:
                    cmd = self._motor_commands[motor_id]
                    command = self._prepare_motor_command(motor_id, cmd['torque'])
                    try:
                        self.serial.write(command)
                        self.serial.flush()
                        time.sleep(0.0005)
                    except Exception as e:
                        pass
            
            # 读取状态并更新PID
            speeds = {0: None, 1: None}
            try:
                while self.serial.in_waiting >= 16:
                    status = self._read_motor_status_raw()
                    if status:
                        motor_id = status['id']
                        speeds[motor_id] = status['speed']
                        # 更新PID控制器
                        self._pids[motor_id].setpoint = self._target_speeds[motor_id]
                        torque_adjustment = self._pids[motor_id](speeds[motor_id])
                        with self._lock:
                            self._motor_commands[motor_id]['torque'] = torque_adjustment

                # 如果两个电机的速度都有值，显示RPM
                if speeds[0] is not None and speeds[1] is not None:
                    print(f"电机0: {speeds[0]:.1f} RPM  电机1: {speeds[1]:.1f} RPM")
                    
            except Exception as e:
                self.serial.reset_input_buffer()
            
            # 保持循环频率
            elapsed = time.time() - loop_start
            if elapsed < period:
                time.sleep(period - elapsed)

    def _prepare_motor_command(self, motor_id, torque):
        """准备电机命令数据"""
        motor_id = max(0, min(motor_id, 15))
        mode = 0x10 | motor_id if torque != 0 else motor_id
        kspd_low, kspd_high = (0x0C, 0x00) if torque != 0 else (0x00, 0x00)
        torque_value = int(torque * 256)
        
        command = bytearray([
            0xFE, 0xEE,
            mode,
            torque_value & 0xFF, (torque_value >> 8) & 0xFF,
            0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00,
            kspd_low, kspd_high
        ])
        
        crc = self._calc_crc16_ccitt(command)
        command.extend([(crc >> 8) & 0xFF, crc & 0xFF])
        return command

    def _read_motor_status_raw(self):
        """读取电机状态"""
        try:
            header = self.serial.read(2)
            while header != b'\xFD\xEE':
                header = header[1:] + self.serial.read(1)
            
            data = self.serial.read(14)
            if len(data) != 14:
                return None

            full_frame = header + data
            received_data = full_frame[:-2]
            received_crc = (full_frame[-2] << 8) | full_frame[-1]
            calc_crc = self._calc_crc16_ccitt(received_data)
            
            if calc_crc != received_crc:
                return None
            
            motor_id = data[0] & 0x0F
            if motor_id not in [0, 1]:
                return None
            
            # 读取速度值（16位）
            speed_raw = (data[3] | (data[4] << 8))
            
            # 处理有符号16位整数
            if speed_raw >= 32768:  # 如果大于等于32768，说明是负数
                speed_raw -= 65536  # 转换为负数
            
            # 转换为实际速度 (rad/s)
            speed_rads = speed_raw * 2 * math.pi / 256.0
            
            # 转换为RPM (rad/s * 60 / (2 * pi))
            speed_rpm = speed_rads * 60 / (2 * math.pi)
            
            return {
                'id': motor_id,
                'speed': speed_rpm,  # 现在返回RPM
            }
            
        except Exception as e:
            return None

    def set_motor_speed(self, motor_id, rpm):
        """设置电机目标转速 (RPM)"""
        with self._lock:
            self._target_speeds[motor_id] = rpm
            if motor_id == 1:
                self._target_speeds[motor_id] = -rpm  # 电机1反向

    def get_motor_status(self, motor_id):
        """获取最新的电机状态"""
        with self._lock:
            if self._motor_status[motor_id]:
                return self._motor_status[motor_id][-1]
            return None

    def close(self):
        """关闭驱动器"""
        try:
            # 再次确保电机速度为0
            self.set_motor_speed(0, 0)
            self.set_motor_speed(1, 0)
            time.sleep(0.1)
            self.stop_comm()
            if self.serial.is_open:
                self.serial.close()
        except:
            pass

    def _calc_crc16_ccitt(self, data):
        """使用查表法计算CRC-CCITT"""
        crc = 0x0000  # 初始值
        for byte in data:
            crc = ((crc >> 8) & 0xFF) ^ self.CRC_CCITT_TABLE[(crc ^ byte) & 0xFF]
        # 翻转字节顺序
        return ((crc << 8) & 0xFF00) | ((crc >> 8) & 0x00FF)

    def command_to_rpm(self, speed_value):
        """
        从命令值反推输出轴RPM
        @param speed_value: 命令中的速度值（16位）
        @return: 输轴的实际RPM值
        """
        # 1. 命令值转换为电机转子rad/s
        rad_s = speed_value / 40.7436
        
        # 2. rad/s转换为电机转子RPM
        motor_rpm = rad_s * 60 / (2 * math.pi)
        
        # 3. 转子RPM转换为输出轴RPM
        output_rpm = motor_rpm / self.REDUCTION_RATIO
        
        return output_rpm

    def rpm_to_command(self, rpm):
        """
        将输出轴目标RPM转换为命令值
        @param rpm: 输出轴目标转速，单位RPM
        @return: (speed_low, speed_high) 速度命令的低字节和高字节
        """
        # 1. 输出轴RPM转换为电机转子RPM
        motor_rpm = rpm * self.REDUCTION_RATIO  # 电机转子需要转得更快
        
        # 2. 转子RPM转换为rad/s
        rad_s = motor_rpm * 2 * math.pi / 60
        
        # 3. 根据协议：wset = wdes * 40.7436
        speed_value = int(rad_s * 40.7436)
        
        return speed_value & 0xFF, (speed_value >> 8) & 0xFF

    def _signal_handler(self, signum, frame):
        """处理Ctrl+C和终止信号"""
        print("\n正在停止电机...")
        try:
            # 设置两个电机速度为0
            self.set_motor_speed(0, 0)
            self.set_motor_speed(1, 0)
            # 等待命令发送完成
            time.sleep(0.1)
            # 关闭驱动器
            self.close()
        finally:
            print("电机已停止")
            sys.exit(0)

def test_both_motors():
    """测��两个电机"""
    driver = MotorDriver()
    try:
        for rpm in [1, -1, 0]:
            driver.set_motor_speed(0, rpm)
            driver.set_motor_speed(1, rpm)
            time.sleep(3)
    finally:
        driver.close()

if __name__ == "__main__":
    test_both_motors()
